package com.example.shop_2212.xq

import android.R.attr
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.base.entity.Comment
import com.example.base.mvvm.BaseActivity
import com.example.base.net.Const
import com.example.shop_2212.R
import com.example.shop_2212.adapter.CommentAdapter
import com.example.shop_2212.adapter.GoodsAdapter
import com.example.shop_2212.adapter.ImgAdapter
import com.example.shop_2212.databinding.ActivityXqBinding
import com.example.shop_2212.utils.GlideUtils
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import com.youth.banner.loader.ImageLoader
import java.text.SimpleDateFormat


@Route(path = "/app/XqActivity")
class XqActivity : BaseActivity<ActivityXqBinding,XqViewModel>() {
    val imgs = mutableListOf<String>()//轮播图地址
    @Autowired
    @JvmField
    var gid:Int = 1

    lateinit var goodsAdapter: GoodsAdapter

    //定义一个属性id ，方便后续添加购物车使用   注意：一定要在请求数据成功后，再次赋值
    var attrId = ""
    //定义一个图片地址，方便后续添加动画使用，  注意：一定要在请求数据成功后，再次赋值
    var img = ""

    lateinit var commentAdapter: CommentAdapter
    val pics = mutableListOf<String>()

    lateinit var imgAdapter: ImgAdapter//发送评论时添加的图片展示

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        ARouter.getInstance().inject(this)
        //动态获取权限
        requestPermissions(arrayOf("android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"),100)
        //请求数据
        viewModel.xq(gid)

        //返回图标
        binding.ivBack.setOnClickListener {
            finish()
        }
        goodsAdapter = GoodsAdapter()
        binding.rvRecommend.adapter = goodsAdapter
        binding.rvRecommend.layoutManager = GridLayoutManager(this,3)
        viewModel.yx()

        //点击加入购物，实现添加功能
        binding.addCar.setOnClickListener {
            viewModel.save(1,attrId,gid)
        }
        //点击购物车，跳转到购物车fragment
        binding.ivCar.setOnClickListener {
            finish()
            ARouter.getInstance().build("/app/ShopActivity").withInt("index",2).navigation()
        }
        //点击分享图标，弹出二维码的对话框，点击确定，实现分享
        binding.ivShare.setOnClickListener {
            showDialog()//显示对话框
        }
        //初始化评论
        commentAdapter = CommentAdapter()
        binding.rvComment.adapter = commentAdapter
        binding.rvComment.layoutManager = LinearLayoutManager(this)

        viewModel.comment(gid,10,1,"0")

        //点击客服，弹出popupWindow 实现模拟发送评论
        binding.ivKefu.setOnClickListener {
            showPop()
        }
    }


    private fun showPop() {
        pics.clear()
        val popupWindow = PopupWindow()
        popupWindow.isFocusable = true//popupwindow获取焦点
        val inflate = LayoutInflater.from(this).inflate(R.layout.pop, null)
        val et = inflate.findViewById<EditText>(R.id.et)
        val addImg = inflate.findViewById<Button>(R.id.addImg)//找到添加图片的按钮
        val rvImg = inflate.findViewById<RecyclerView>(R.id.rv_img)//找到展示图片的列表
        imgAdapter = ImgAdapter()
        rvImg.adapter = imgAdapter
        rvImg.layoutManager = GridLayoutManager(this,3)
        addImg.setOnClickListener {
            //不超过四张图片
            if(imgAdapter.data.size==4){
                ToastUtils.showLong("最多能接收4张图片")
            }else{
                imgAdapter.data.add("http://10.161.9.80:8080/crmebimage/public/operation/2021/12/25/0427b90c74b64a03ae3e7e5c628ef7d69038aimgou.jpg")
                imgAdapter.notifyDataSetChanged()
            }
        }
        val send = inflate.findViewById<Button>(R.id.send)
        send.setOnClickListener {
            commentAdapter.data.add(0,Comment("http://10.161.9.80:8080/crmebimage/public/operation/2021/12/25/0427b90c74b64a03ae3e7e5c628ef7d69038aimgou.jpg",
            et.text.toString(),SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis()),0,"","zhangsan", emptyList(),5,"",0))
            commentAdapter.notifyDataSetChanged()
            popupWindow.dismiss()//关闭弹出框
        }


        popupWindow.width = LayoutParams.MATCH_PARENT
        popupWindow.height = LayoutParams.WRAP_CONTENT
        popupWindow.isOutsideTouchable = true//点击空白处消失
        popupWindow.contentView = inflate

        popupWindow.showAtLocation(binding.ivKefu,Gravity.BOTTOM,0,0)
    }

    private fun showDialog() {
        val view = LayoutInflater.from(this).inflate(R.layout.dialog, null)
        val dialog = AlertDialog.Builder(this)
            .setTitle("提示")
            .setView(view)
            .create()
        val barcodeEncoder = BarcodeEncoder()//二维码位图生成器
        val bitmap =
            barcodeEncoder.encodeBitmap(gid.toString(), BarcodeFormat.QR_CODE, 200, 200)//生成图片
        view.findViewById<ImageView>(R.id.iv).setImageBitmap(bitmap)//显示图片
        //点击实现分享
        view.findViewById<Button>(R.id.yes).setOnClickListener {
            val image: UMImage = UMImage(this@XqActivity, bitmap) //bitmap文件
            ShareAction(this).withText("hello").withMedia(image)
                .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                .setCallback(object :UMShareListener{
                    override fun onStart(p0: SHARE_MEDIA?) {
                    }

                    override fun onResult(p0: SHARE_MEDIA?) {
                    }

                    override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                        ToastUtils.showLong(p1?.message)
                    }

                    override fun onCancel(p0: SHARE_MEDIA?) {

                    }
                })
                .open()
            dialog.dismiss()//对话框消失
        }
        //点击取消，关闭对话框
        view.findViewById<ImageView>(R.id.no).setOnClickListener {
            dialog.dismiss()
        }

        dialog.show()//显示对话框
    }

    override fun initData() {
        viewModel.xqSuccess.observe(this){
            if(it.code==200){
                attrId = it.data.productValue.values.toList().get(0).id.toString()//获取属性id
                img = it.data.productInfo.image//获取图片网址
                binding.info = it.data.productInfo//给页面中info赋值
                imgs.add(it.data.productInfo.image)
                imgs.add(it.data.productInfo.image)
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null) {
                                if (imageView != null) {
                                    Glide.with(context).load(path).into(imageView)
                                }
                            }
                        }
                    })
                    .start()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.yxSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                goodsAdapter.data.clear()
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
            }
        }
        viewModel.saveSuccess.observe(this){
            ToastUtils.showLong(it.message)
            //成功，添加动画
            if(it.code==Const.RESULT_OK){
                //发送动画---图片
                val imageView = ImageView(this)
                val layoutParams = LayoutParams(200, 200)//图片大小
                imageView.layoutParams = layoutParams
                GlideUtils.loadImage(this,img,imageView)
                binding.clXq.addView(imageView)//在页面上显示图片
                //添加动画效果
                val width = windowManager.defaultDisplay.width.toFloat()//浮点类型的屏幕宽
                val height = windowManager.defaultDisplay.height.toFloat()//浮点类型的屏幕高
                val translationX = ObjectAnimator.ofFloat(imageView, "translationX", 0f, width)
                val translationY = ObjectAnimator.ofFloat(imageView, "translationY", 0f, height)
                val animatorSet = AnimatorSet()
                animatorSet.duration = 2000
                animatorSet.play(translationX).with(translationY)
                animatorSet.start()

                animatorSet.addListener(object:Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        //动画结束--图片移除
                        binding.clXq.removeView(imageView)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })

            }
        }
        viewModel.commentSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                commentAdapter.data.clear()
                commentAdapter.data.addAll(it.data.list)
                commentAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun getViewModel(): Class<XqViewModel>  = XqViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_xq
}